#!/bin/bash

echo "🔧 智能启动后端服务器..."
echo "=========================="

# 检查端口5005是否被占用
PORT_PID=$(lsof -ti :5005)

if [ ! -z "$PORT_PID" ]; then
    echo "⚠️  端口5005已被占用 (PID: $PORT_PID)"
    echo "🛑 正在停止现有服务器..."
    kill $PORT_PID
    sleep 2
    
    # 再次检查
    PORT_PID=$(lsof -ti :5005)
    if [ ! -z "$PORT_PID" ]; then
        echo "❌ 强制停止服务器..."
        kill -9 $PORT_PID
        sleep 1
    fi
    echo "✅ 现有服务器已停止"
fi

echo ""
echo "🚀 启动新的服务器..."

# 检查启动哪个版本
if [ "$1" = "ts" ]; then
    echo "📦 编译 TypeScript 版本..."
    npx tsc server/index.ts --outDir server/dist --module commonjs --target es2020 --esModuleInterop --allowSyntheticDefaultImports --resolveJsonModule
    
    if [ $? -eq 0 ]; then
        echo "✅ 编译成功!"
        echo "🚀 启动 TypeScript 服务器..."
        node server/dist/index.js
    else
        echo "❌ 编译失败!"
        exit 1
    fi
else
    echo "🚀 启动 JavaScript 服务器..."
    node server/server.js
fi
